package com.hrt.manage.users.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hrt.base.BaseController;
import com.hrt.bean.Role;
import com.hrt.bean.UserVO;
import com.hrt.bean.UsersInfor;
import com.hrt.bean.ViewResource;
import com.hrt.manage.access.service.AccessService;
import com.hrt.manage.role.service.UserRoleService;
import com.hrt.manage.users.service.UserInforService;
import com.hrt.util.MD5Tool;
import com.hrt.util.WebParams;

@Controller
@RequestMapping(value = "manage/user")
public class UserInforController extends BaseController<UsersInfor> {

	@Autowired
	private UserInforService userInforService;

	@Autowired
	private UserRoleService userRoleSerivce;

	@Autowired
	private AccessService accessService;

	public UserInforController() {

	}

	public UserInforService getUserInforService() {
		return userInforService;
	}

	public void setUserInforService(UserInforService userInforService) {
		this.userInforService = userInforService;
	}

	public List<UsersInfor> getList() {
		return list;
	}

	public void setList(List<UsersInfor> list) {
		this.list = list;
	}

	/**
	 * 
	 * @param pageIndex
	 * 
	 * @param pageSize
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/queryByPage")
	@ResponseBody
	public Map queryByPage(
			@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			HttpServletRequest request) {
		Map resultMap = new HashMap();

		if (pageSize == null || "".equals(pageSize)) {
			pageSize = 30;
		}
		if (pageIndex == null || "".equals(pageIndex)) {
			pageIndex = 1;
		}
		setPageIndex(pageIndex);

		setPageSize(pageSize);

		setTotalCount(userInforService.totalCount());

		List<UsersInfor> resultList = userInforService.queryByPage(
				getPageIndex(), getPageSize());
		setList(resultList);

		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();

		resultMap.put("pageResult", page);
		return resultMap;
	}

	/**
	 * 
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(HttpServletRequest request) {
		ModelAndView view = new ModelAndView();

		list = userInforService.queryByPage(getPageIndex(), getPageSize());
		setTotalCount(userInforService.totalCount());
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();

		view.addObject("pageResult", page);
		// request.getSession().setAttribute("pageResult", page);
		return view;

	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody Long[] delete(
			@RequestParam(value = "ids", required = true) String ids,
			HttpServletResponse response) throws IOException {
		Long[] idArr = null;
		ModelAndView view = new ModelAndView();

		if (ids != null) {
			if (ids.indexOf(",") != -1) {
				String[] idStrs = ids.split(",");
				idArr = new Long[idStrs.length];
				for (int idx = 0; idx < idStrs.length; idx++) {
					idArr[idx] = Long.parseLong(idStrs[idx]);
				}
			} else {
				idArr = new Long[] { Long.parseLong(ids) };
			}

		}
		try {
			userInforService.deleteById(idArr);

			return idArr;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void save(@ModelAttribute("userInfor") UsersInfor user,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView model = new ModelAndView();
		System.out.println("save");

		try {
			if ("".equals(user.getLoginName()) || user.getLoginName() == null
					|| user.getPassword() == null
					|| "".equals(user.getPassword())) {

				throw new Exception("登陆名或密码未空");
			}
			user.setPassword(MD5Tool.MD5(user.getPassword()));
			user.setStatus(new Integer(0));
			userInforService.saveUser(user);

			response.sendRedirect("list.do");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/show")
	@ResponseBody
	public Map show(@RequestParam(value = "id", required = true) String userId,
			HttpServletRequest request, HttpServletResponse response) {

		Map map = new HashMap();
		if (userId != null && !"".equals(userId)) {
			// Map resultMap=new HashMap<K, V>();
			System.out.println("showshowshowshowshow " + userId);
			UsersInfor user = this.userInforService
					.getUserByid(new Long(userId));
			if (user != null) {
				map = transBean2Map(user);
			}

		}
		return map;

	}

	@RequestMapping(value = "/lockUser")
	@ResponseBody
	public String lockUser(
			@RequestParam(value = "id", required = true) String userId,
			HttpServletRequest request, HttpServletResponse response) {

		if (userId != null && !"".equals(userId)) {
			// Map resultMap=new HashMap<K, V>();
			System.out.println("showshowshowshowshow " + userId);
			UsersInfor user = this.userInforService
					.getUserByid(new Long(userId));
			if (user != null) {
				user.setStatus(new Integer(1));
				this.userInforService.updateUser(user);
				return "success";
			}

		}
		return "fail";

	}

	@RequestMapping(value = "/unlockUser")
	@ResponseBody
	public String unlockUser(
			@RequestParam(value = "id", required = true) String userId,
			HttpServletRequest request, HttpServletResponse response) {

		if (userId != null && !"".equals(userId)) {
			// Map resultMap=new HashMap<K, V>();
			System.out.println("showshowshowshowshow " + userId);
			UsersInfor user = this.userInforService
					.getUserByid(new Long(userId));
			if (user != null) {
				user.setStatus(new Integer(0));
				this.userInforService.updateUser(user);
				return "success";
			}

		}
		return "fail";

	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public void update(@ModelAttribute("userInfor") UsersInfor user,
			HttpServletRequest request, HttpServletResponse response) {
		System.out.println("update");
		System.out.println(user.getLoginName());
		System.out.println(user.getPassword());
		System.out.println(user.getNote());

		try {
			if ("".equals(user.getLoginName()) || user.getLoginName() == null
					|| user.getPassword() == null
					|| "".equals(user.getPassword())) {

				throw new Exception("登陆名或密码未空");
			}
			user.setPassword(MD5Tool.MD5(user.getPassword()));
			userInforService.updateUser(user);

			response.sendRedirect("list.do");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	 */
	@RequestMapping(value = "/welcome")
	public void welcome(HttpServletResponse response) {
		try {
			response.sendRedirect("/manage/login.jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 后台用户登录
	 * 
	 * @param username
	 * @param password
	 */
	@RequestMapping(value = "/perLogin", method = RequestMethod.POST)
	public ModelAndView login(
			@RequestParam(value = "loginName", required = true) String username,
			@RequestParam(value = "pwd", required = true) String password,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();

		if ("".equals(username) || username == null || password == null
				|| "".equals(password)) {

			mv.setViewName("manage/login");
			mv.addObject("status", "-1");
			mv.addObject("msg", "登陆名或密码未空");
			return mv;
		}
		try {
			UserVO user = userInforService.getUserByUsernameAndPassword(
					username, MD5Tool.MD5(password));
			if (user != null) {
				List<Role> roles = userRoleSerivce.queryRolesByUserId(user
						.getUserId());
				mv.setViewName("manage/selectRole");

				mv.addObject("role", roles);
				mv.addObject("status", 0);// "登陆成功，请选择你要登陆的角色"
				mv.addObject("msg", "登陆成功，请选择你要登陆的角色");
				mv.addObject("user", user);
				return mv;
			} else {
				mv.setViewName("manage/login");
				mv.addObject("status", -2);// 登陆名或密码未空
				mv.addObject("msg", "登陆失败");
				return mv;
			}

		} catch (Exception e) {
			mv.addObject("manage/login");
			mv.addObject("status", -2);// 登陆名或密码未空
			mv.addObject("msg", "登陆失败");
			// view.addObject("error_msg", "登陆失败");
			e.printStackTrace();
			return mv;

		}

	}

	@RequestMapping(value = "/logout")
	public void logout(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView();
		UserVO user = getOnlineManager(request, response);

		if (user != null) {
			request.getSession().removeAttribute(WebParams.ON_LINE_MANAGER);
		}
		try {
			response.sendRedirect(request.getContextPath()
					+ "/manage/login.jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 确认登陆
	 * 
	 * @param roleId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/confirm", method = RequestMethod.POST)
	public ModelAndView confirm(
			@ModelAttribute(value = "loginfrm") UserVO user,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView();
		System.out.println("------------->"+user.getLoinName());
		List<String> urls = new ArrayList<String>();
		if (user != null) {
			List<ViewResource> list = accessService.queryAccByScope(
					user.getRole(), new Integer(0));

			user.setUrls(list);
			setOnlineManager(user, request, response);
		}
		view.setViewName("manage/main");
		return view;

	}

}
